import {Scope} from 'lib/scopeFactory'
import TimeStore from 'lib/stores/time-store'
import dispatcher from 'lib/dispatcher'
import {coreApi,sortMap,parseToChart,parseToTopbar} from '../apis/core-util'
import _ from 'underscore'

export default class BaseScope extends Scope {
  constructor(props, context) {
    super(props, context);

    this.dataSource = [];
  }

  state() {
    let args = [{}].concat(_.chain(this.dataSource).pluck('$state').value());
    return _.extend.apply(this, args);
  }

  _handle(payload) {
    var payLoadName = payload.$type.toLowerCase()
    if(this['$' + payLoadName]) {
      this['$' + payLoadName](payload)
    } else {
      for (var i = 0; i < this.dataSource.length; i++) {
        let item = this.dataSource[i];
        if(item['$' + payLoadName]) {
          item['$' + payLoadName](payload);
          break;
        } // if
      } // for
    } // else
  }

  _emit(view, callback) {
    if(!this.__unbind){
      if (callback) {
        view.setState(this.state(), callback)
      } else {
        view.setState(this.state())
      }
    }
  }

  $load() {
    for (let i = 0; i < this.dataSource.length; i++) {
      let item = this.dataSource[i];
      if (item.$load) {
        item.$load.call(item);
      }
    }
  }

  $unload() {
    for (let i = 0; i < this.dataSource.length; i++) {
      let item = this.dataSource[i];
      if (item.$unload) {
        item.$unload.call(item);
      }
    }
  }
}
